//
//  JokeController.m
//  MINFOBBS
//
//  Created by juvid on 13-11-20.
//  Copyright (c) 2013年 minfo. All rights reserved.
//

#import "JokeController.h"
#import "JokeCell.h"
#import "MainSearchViewController.h"
#import "SBJson.h"
#import "DetectionSystemVersion.h"
#import "UIColor+expanded.h"
@interface JokeController ()

@end

@implementation JokeController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationItem setHidesBackButton:YES];
   self.navigationItem.titleView=[DetectionSystemVersion SetBarTitle:@"百事搜"];
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    if (self.isSelf) {
        [self SetCellHight];
    }
    else{
         [self BackButton];
        pageLimit=5;
        pageStart=0;
        loadMore=[[LoadMore alloc]init];
        loadMore.frame= CGRectMake(0, 0, 320, 32);
        [self.tableView addSubview:loadMore];
        self.tableView.showsVerticalScrollIndicator=YES;
        self.tableView.bounces=YES;
//        NSLog(@"%@",self.strKey);
        [self GetDatas];
    }
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)BackButton{
    UIButton *btnBack=[[DetectionSystemVersion alloc]BackButton];
    [btnBack addTarget:self action:@selector(BackReturn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem=backItem;
    
}
#pragma mark 导航栏按钮事件
-(void)BackReturn:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)SetCellHight{
    CGSize sizeFrame;
    arrRowHight=[[NSMutableArray alloc]init];
   
    for (int i=0; i<self.arrReturn.count; i++) {
        NSArray *arr=[[[self.arrReturn objectAtIndex:i] objectForKey:@"Properties"] objectForKey:@"Property"];
        NSString *str;
        if (self.isRidele) {
            for (int i=0; i<arr.count; i++) {
                if ([[[arr objectAtIndex:i] objectForKey:@"name"] isEqual:@"谜面"]) {
                    str=[[arr objectAtIndex:i] objectForKey:@"text"];
                }
            }
//             str=[[arr objectAtIndex:0] objectForKey:@"text"];
        }
        else{
            for (int i=0; i<arr.count; i++) {
                if ([[[arr objectAtIndex:i] objectForKey:@"name"] isEqual:@"内容"]) {
                    str=[[arr objectAtIndex:i] objectForKey:@"text"];
                }
            }
        }
        arr=nil;
        if (str.length!=0) {
            sizeFrame =[str sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(280, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
            [arrRowHight addObject:[NSString stringWithFormat:@"%f",sizeFrame.height]];
            //            NSLog(@"%@",arrRowHight);
        }
    }
    [self.tableView reloadData];
    loadMore.frame=CGRectMake(0, self.tableView.contentSize.height-35, 320, 32);
}
- (void)viewWillDisappear:(BOOL)animated{
    [tRequest clearDelegatesAndCancel];
    [tRequest cancel];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [NSThread cancelPreviousPerformRequestsWithTarget:self];
}
#pragma mark 异步数据请求
-(void)GetDatas{
    loadMore.loadingTitle.text=@"正在加载...";
    [loadMore.loadingAni startAnimating];
    tRequest=[[[ScreenAccess alloc]init]ASIGetSearch:self.strKey Start:pageStart Limit:pageLimit];
    [tRequest setDelegate:self];
    [tRequest setUsername:@"allMessage"];
    
}
-(void)requestFinished:(ASIHTTPRequest*)request{
    
    NSString *response = [request responseString];
    SBJsonParser * parser = [[SBJsonParser alloc] init];
    NSMutableDictionary *Result = [parser objectWithString:response];
    
    if ([request.username isEqual:@"allMessage"]){
        BOOL IsSuccess=[[[Result objectForKey:@"Response"]objectForKey:@"status"]integerValue]==200?YES:NO;
        if (IsSuccess==YES) {
            
            if (self.arrReturn==nil) {
                self.arrReturn=[[NSMutableArray alloc]init];
            }
            [self.arrReturn addObjectsFromArray:[[[[[[Result objectForKey:@"Response"] objectForKey:@"Categories"] objectForKey:@"Category"] objectAtIndex:0]objectForKey:@"Items"] objectForKey:@"Item"]];
            [self SetCellHight];
            loadMore.loadingTitle.text=@"上拉加载更多";
            [loadMore.loadingAni stopAnimating];
        }
    }
    else if([request.username isEqual:@"weather"]){
    }
    loadingmore=NO;

}

-(void)requestFailed:(ASIHTTPRequest*)request{
    [loadMore.loadingAni stopAnimating];
    loadMore.loadingTitle.text=@"无网络";
    loadingmore=NO;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    
    return self.arrReturn.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"JokeCell";
    JokeCell *cell =(JokeCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleGray;
    cell.textLabel.backgroundColor=[UIColor clearColor];
    if (indexPath.row%2==1) {
        UIView *vie=[[UIView alloc]init];
        vie.backgroundColor=[UIColor colorWithHexString:@"0xf3f3f3"];
        cell.backgroundView=vie;
    }
    else{
        cell.backgroundColor=[UIColor whiteColor];
    }
    NSArray *arr=[[[self.arrReturn objectAtIndex:indexPath.row] objectForKey:@"Properties"] objectForKey:@"Property"];
    if (self.isRidele) {
        
            cell.labContent.text=[[arr objectAtIndex:0] objectForKey:@"text"];
    }
    else{
        for (int i=0; i<arr.count; i++) {
            if ([[[arr objectAtIndex:i] objectForKey:@"name"] isEqual:@"内容"]) {
               cell.labContent.text=[[arr objectAtIndex:i] objectForKey:@"text"];            }
        }
    }
    [cell.btnMessage setTitle:cell.labContent.text forState:UIControlStateNormal];
    [cell.btnMessage addTarget:self action:@selector(PressMessage:) forControlEvents:UIControlEventTouchUpInside];
    
    [cell.btnShare addTarget:self action:@selector(PressShare:) forControlEvents:UIControlEventTouchUpInside];
    [cell.btnShare setTitle:cell.labContent.text forState:UIControlStateNormal];
//    NSLog(@"%@",self.arrContent);
//    NSLog(@"<#string#>")
    // Configure the cell...
    
    return cell;
}
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    float rowHight = 0.0;
    if (arrRowHight.count>0) {
        rowHight=[[arrRowHight objectAtIndex:indexPath.row] floatValue];
    }
       return rowHight+36;
    
}
//-(float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    if (self.isSelf) {
//        return 30;
//
//    }
//       return 0;
//}
//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//       UIView *result;
//    if (self.isSelf) {
//        result=[[UIView alloc]init];
//        UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, 200, 30)];
//        lab.text=@"开心一刻";
//        lab.font=[UIFont systemFontOfSize:14];
//        [result addSubview:lab];
//        result.backgroundColor=[UIColor clearColor];
//
//    }
//       return result;
//}

-(float)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 35;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *result;
    result=[[UIView alloc]init];
    result.backgroundColor=[UIColor clearColor];
    if (self.isSelf) {
        UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 3)];
        img.image=[UIImage imageNamed:@"footLine"];
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, 3, self.tableView.frame.size.width, 35)];
        [btn setTitle:@"查看更多" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(PrseeMore) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitleColor:[UIColor colorWithHexString:@"0xb7b7b7"] forState:UIControlStateNormal];
        btn.titleLabel.font=[UIFont systemFontOfSize:14];
        [result addSubview:btn];
        [result addSubview:img];
    }
    return result;
}
- (MainSearchViewController *)menuContainerViewController {
    return (MainSearchViewController *)self.parentViewController;
}
-(void)PrseeMore{
//    if (self.isSelf) {
        JokeController *jokecon=[[JokeController alloc]init];
    jokecon.isRidele=self.isRidele;
    jokecon.strKey=self.strKey;
    [ [self menuContainerViewController].navigationController  pushViewController:jokecon animated:YES];
//    }
  
   
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    PrevCGPoint=scrollView.contentOffset;
    if (PrevCGPoint.y>scrollView.contentSize.height-scrollView.frame.size.height) {
        if (loadingmore) return;
        loadingmore = YES;
        pageStart++;
        [self GetDatas];
    }
}
//-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
//{
//    if ([scrollView isEqual:table]) {
//        PrevCGPoint=scrollView.contentOffset;
//        if (PrevCGPoint.y>scrollView.contentSize.height-scrollView.frame.size.height) {
//            if (loadingmore) return;
//            loadingmore = YES;
//            PageIndex++;
//            if (customers.count<self.total) {
//                [loadingAni startAnimating];
//                loadingTitle.text=@"加载中请稍后";
//                [self GetDatas:PageIndex];
//            }
//        }
//        
//    }
//}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.isRidele) {
        NSArray *arr=[[[self.arrReturn objectAtIndex:indexPath.row] objectForKey:@"Properties"] objectForKey:@"Property"];
        NSString *str;
        for (int i=0; i<arr.count; i++) {
            if ([[[arr objectAtIndex:i] objectForKey:@"name"] isEqual:@"谜底"]) {
                str=[[arr objectAtIndex:i] objectForKey:@"text"];
            }
        }
        UIAlertView *alr=[[UIAlertView alloc]initWithTitle:@"谜底" message:str delegate:Nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alr show];
    }
    // Navigation logic may go here, for example:
//    // Create the next view controller.
//    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
//
//    // Pass the selected object to the new view controller.
//    
//    // Push the view controller.
//    [self.navigationController pushViewController:detailViewController animated:YES];
//    [tableView ]
}
-(void)PressMessage:(UIButton *)buton{
    [self sendSMS:buton.currentTitle recipientList:Nil];
}
-(void)PressShare:(UIButton *)button{
    NSString *message = button.currentTitle;
    NSArray *postItems = @[message];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]
                                            initWithActivityItems:postItems
                                            applicationActivities:nil];
    activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,
                                         UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll,UIActivityTypeMessage];
    [self presentViewController:activityVC animated:YES completion:nil];

}
- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    
    if([MFMessageComposeViewController canSendText]){
        controller.body = bodyOfMessage;
        controller.recipients = recipients;
        controller.messageComposeDelegate = self;
        [self presentViewController:controller animated:YES completion:Nil];
    }
}
// 处理发送完的响应结果
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:Nil];
    [self ShowHUD];
    if (result==MessageComposeResultCancelled) {
        HUD.labelText=@"取消了发送";
        HUD.customView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"HUDProblem"]];
        HUD.mode = MBProgressHUDModeCustomView;
        NSLog(@"取消");
        
    }
    else if(result==MessageComposeResultSent){
        HUD.customView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"HUDTrue"]];
        HUD.mode = MBProgressHUDModeCustomView;
        HUD.labelText=@"发送成功";
        
    }
    else{
        HUD.labelText=@"发送失败";
        HUD.customView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"HUDFlase"]];
        HUD.mode = MBProgressHUDModeCustomView;
        
    }
    [HUD hide:YES afterDelay:1];
}

-(void)ShowHUD{
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.delegate = self;
    HUD.labelText = @"";
    [self.view addSubview:HUD];
    [HUD show:YES];
}

@end
